package listbyorder.access001_100.test40;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/31 14:59
 */
public class Solution1 {

    // 经典回溯算法
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(new ArrayList<Integer>(), res, 0, target, 0, candidates);
        return res;
    }

    private void dfs(ArrayList<Integer> path, List<List<Integer>> res, int sum, int target, int s, int[] candidates) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (sum > target || s == candidates.length) return;
        for (int i = s; i < candidates.length; i++) {
            if (i > s && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            dfs(path, res, sum + candidates[i], target, i + 1, candidates);
            path.remove(path.size() - 1);
        }
    }
}
